﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Collections.ObjectModel;

namespace CommunitySystem.PageView.公务员选拔
{
    public partial class PhotoImportControl : UserControl
    {
        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialSelectionServiceClient client = null;
        public PhotoImportControl()
        {
            InitializeComponent();
            client = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            client.ValidateHasPhotoCompleted += new EventHandler<PublicOfficialSelectionService.ValidateHasPhotoCompletedEventArgs>(client_ValidateHasPhotoCompleted);
            client.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(client_UploadFileCompleted);
            client.UpdateHasPotoCompleted += new EventHandler<PublicOfficialSelectionService.UpdateHasPotoCompletedEventArgs>(client_UpdateHasPotoCompleted);
            
        }

        void client_UpdateHasPotoCompleted(object sender, PublicOfficialSelectionService.UpdateHasPotoCompletedEventArgs e)
        {
            UploadFileInfo f = e.UserState as UploadFileInfo;
            f.HasFinished = "/CommunitySystem;component/Images/ViewDesign/ok.png";
        }

        void client_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            UploadFileInfo f = e.UserState as UploadFileInfo;
            f.CurrentNo = f.parts - f.Context.Count;
            if (f.Context.Count > 0)
            {
                client.UploadFileAsync("photo", f.DisplayName, f.Context[0], false, f);

                f.Context.RemoveAt(0);
            }
            else
            {
                client.UpdateHasPotoAsync(f.Name, true, f.DisplayName,f);
            }
        }

        /// <summary>
        /// 验证那些人是否已经有照片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ObservableCollection<CommunitySystem.PublicOfficialSelectionService.Emp_BasicInfoModel> allpeople = null;
        ObservableCollection<CommunitySystem.PublicOfficialSelectionService.Emp_BasicInfoModel> hasphoto = null;
        void client_ValidateHasPhotoCompleted(object sender, PublicOfficialSelectionService.ValidateHasPhotoCompletedEventArgs e)
        {
            allpeople = e.Result;
            var notin = fileNames.Where(c => allpeople.Where(d => d.CardNo.ToLower() == c.ToLower()).Count() <= 0);//from c in allpeople
            foreach (var r in allpeople)
            {
                UploadFileInfo f = files.Where(c => c.Name.ToLower() == r.CardNo.ToLower()).FirstOrDefault();
                if (f != null)
                {
                    f.HasFinished = "/CommunitySystem;component/Images/ViewDesign/add.png";
                    f.XingMin = r.Name;
                }
            }
            if (notin.Count() > 0)//有不卡号不匹配的情况
            {
                string card = string.Empty;
                foreach (var p in notin)
                {
                    card += p + "\n\t";
                }
                if (MessageBox.Show("以下图片名称不匹配数据库中人员卡号，是否导入已匹配图片?\n\t" + card, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    hasphoto = new ObservableCollection<PublicOfficialSelectionService.Emp_BasicInfoModel>(e.Result.Where(c => c.HasPhoto == true));
                    if (hasphoto.Count() > 0)//有已经导入的
                    {
                        string hasphotoNames = string.Empty;
                        foreach (var p in hasphoto)
                        {
                            if (hasphoto.IndexOf(p) == hasphoto.Count - 1)
                                hasphotoNames += p.Name + p.CardNo;
                            else
                                hasphotoNames += p.Name + p.CardNo + "\n\t";
                        }
                        if (MessageBox.Show("以下人员图片已导入，是否覆盖?\n\t" + hasphotoNames, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)//覆盖掉已导入的
                        {
                            foreach (var a in allpeople)
                            {
                                var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
                                client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                                f.Context.RemoveAt(0);
                            }
                        }else//不覆盖
                        {
                            foreach (var a in allpeople)
                            {
                                var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
                                int count = hasphoto.Where(c => f.Name.ToLower() == c.CardNo.ToLower()).Count();
                                if (count <= 0)
                                {
                                    client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                                    f.Context.RemoveAt(0);
                                }
                            }
                        }
                    }
                    else//没有已经导入的
                    {
                        foreach (var a in allpeople)
                        {
                            var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
                            if (f != null)
                            {
                                client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                                f.Context.RemoveAt(0);
                            }
                        }
                    }

                }
            }
            else//没有卡号不匹配的
            {
                hasphoto = new ObservableCollection<PublicOfficialSelectionService.Emp_BasicInfoModel>(e.Result.Where(c => c.HasPhoto == true));
                if (hasphoto.Count() > 0)//有已经导入的
                {
                    string hasphotoNames = string.Empty;
                    foreach (var p in hasphoto)
                    {
                        if (hasphoto.IndexOf(p) == hasphoto.Count - 1)
                            hasphotoNames += p.Name + p.CardNo;
                        hasphotoNames += p.Name + p.CardNo + "\n\t";
                    }
                    if (MessageBox.Show("以下人员图片已导入，是否覆盖?\n\t" + hasphotoNames, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)//覆盖掉已导入的
                    {
                        foreach (var a in allpeople)
                        {
                            var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
                            client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                            f.Context.RemoveAt(0);
                        }
                    }else//不覆盖
                    {
                        foreach (var a in allpeople)
                        {
                            var f = files.Where(c => c.Name == a.CardNo).FirstOrDefault();
                            int count = hasphoto.Where(c => f.Name.ToLower() == (c.CardNo.ToLower())).Count();
                            if (count <= 0)
                            {
                                client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                                f.Context.RemoveAt(0);
                            }
                        }
                    }
                }
                else//没有已经导入的
                {
                    foreach (var a in allpeople)
                    {
                        var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
                        client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                        f.Context.RemoveAt(0);
                    }
                    //hasphoto = new ObservableCollection<PublicOfficialSelectionService.Emp_BasicInfoModel>(e.Result.Where(c => c.HasPhoto == true));
                    //if (hasphoto.Count() > 0)//有已经导入的
                    //{
                    //    string hasphotoNames = string.Empty;
                    //    foreach (var p in hasphoto)
                    //    {
                    //        if (hasphoto.IndexOf(p) == hasphoto.Count - 1)
                    //            hasphotoNames += p.Name + p.CardNo;
                    //        hasphotoNames += p.Name + p.CardNo + "\n\t";
                    //    }
                    //    SilverlightMessageBoxLibrary.CustomMessage cm2 = new SilverlightMessageBoxLibrary.CustomMessage("以下人员图片已导入，是否覆盖?\n\t" + hasphotoNames, SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
                    //    cm2.OKButton.Click += (sender2, e2) =>//覆盖掉已导入的
                    //    {
                    //        foreach (var a in allpeople)
                    //        {
                    //            var f = files.Where(c => c.Name == a.CardNo).FirstOrDefault();
                    //            client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                    //            f.Context.RemoveAt(0);
                    //        }
                    //    };
                    //    cm2.CancelButton.Click += (sender2, e2) =>//不覆盖
                    //    {
                    //        foreach (var a in allpeople)
                    //        {
                    //            var f = files.Where(c => c.Name == a.CardNo).FirstOrDefault();
                    //            int count = hasphoto.Where(c => f.Name==(c.CardNo)).Count();
                    //            if (count <= 0)
                    //            {
                    //                client.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                    //                f.Context.RemoveAt(0);
                    //            }
                    //        }
                    //    };
                    //}
                }
            }
        }

        
        private List<string> fileNames = new List<string>();
        private ObservableCollection<UploadFileInfo> files = new ObservableCollection<UploadFileInfo>();
        private List<string> extendName = new List<string>()
        {
            "png",
            "jpg",
            "bmp"
        };
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            fileNames.Clear();
            //files.Clear();
            var openFile = new OpenFileDialog() { Multiselect = true, Filter = "*.png|*.png|*.jpg |*.jpg|*.bmp |*.bmp|All(所有文件)|*.*" };
            string invalidateNames = string.Empty;
            if (openFile.ShowDialog() == true)
            {
                foreach (var f in openFile.Files)
                {
                    string[] onefile = f.Name.Split('.');                    
                    UploadFileInfo info = new UploadFileInfo();
                    if (onefile.Length > 0)
                    {
                        if (extendName.Contains(onefile[onefile.Length - 1].ToLower()))
                        {
                            fileNames.Add(onefile[0]);
                            info.Name = onefile[0];
                            info.DisplayName = f.Name;
                            info.HasFinished = "/CommunitySystem;component/Images/ViewDesign/delete.png";
                            Stream stream = f.OpenRead();
                            int b = 0;
                            while (stream.Position > -1 && stream.Position < stream.Length)
                            {
                                if (stream.Length - stream.Position >= 16000)
                                {
                                    b = 16000;
                                }
                                else
                                {
                                    b = (int)(stream.Length - stream.Position);
                                }

                                byte[] filebyte = new byte[b];
                                stream.Read(filebyte, 0, b);
                                if (info.Context == null)
                                    info.Context = new List<byte[]>();
                                info.Context.Add(filebyte);
                            }
                            info.parts = info.Context.Count;
                            files.Add(info);
                        }
                        else
                        {
                            invalidateNames += f.Name + "\n\t";
                        }
                    }
                    
                }
                if (!string.IsNullOrEmpty(invalidateNames))
                {
                    if (MessageBoxResult.OK == MessageBox.Show("以下文件格式错误，不能导入:\n\t" + invalidateNames, "", MessageBoxButton.OKCancel))
                    {
                        listBox1.ItemsSource = files;
                        client.ValidateHasPhotoAsync(new System.Collections.ObjectModel.ObservableCollection<string>(fileNames), EHR.Common.Session.LoginUser.LoginName);
                    }
                }
                else
                {
                    listBox1.ItemsSource = files;
                    client.ValidateHasPhotoAsync(new System.Collections.ObjectModel.ObservableCollection<string>(fileNames), EHR.Common.Session.LoginUser.LoginName);
                }
                
                //SilverlightMessageBoxLibrary.CustomMessage cm = new SilverlightMessageBoxLibrary.CustomMessage("一下文件格式错误，不能导入:\n\t"+invalidateNames, SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
                //cm.Show();
                //cm.OKButton.Click += (sender1, e1) =>
                //{
               
                //};
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            var info = img.DataContext as UploadFileInfo;
            if (info != null)
            {
                if (info.HasFinished.Equals("/CommunitySystem;component/Images/ViewDesign/delete.png"))
                {
                    files.Remove(info);
                }
            }
        }

      
    }
}
